package org.skyui.core;

import org.skyui.annotations.Singleton;

public class AccessControl {

	public static boolean isAccessible(Menu menu, UIApplication app) {
		return isAccessible(menu.getRoles(), app.getRole(), menu.getProductEditions(), 
				app.getProductEdition());
	}

	public static boolean isAccessible(String[] roles, String[] productEditions, UIApplication app) {
		if (app ==null){
		    return false;  
		}else{
	    return isAccessible(roles, app.getRole(), productEditions, 
				app.getProductEdition());
		}
	}
	
	public static boolean isAccessible(String[] roles, String role, String[] productEditions, 
			String productEdition) {
		return match(roles, role) && match(productEditions, 
				productEdition);
	}
	
	
	static boolean match(String[] allowed, String actual) {
		if (allowed == null || allowed.length == 0)
			return false;
		for (String a: allowed) {
			if (a.equals("ALL") || a.equals(actual)) {
				return true;
			}
		}
		return false;
	}

	public static boolean isSingleton(Class beanClass,
		UIApplication instance) {
	    Singleton s = (Singleton) beanClass.getAnnotation(Singleton.class);
	    if (s == null) 
		return false;
	    return isAccessible(s.roles(), s.productEditions(), instance);
	}
	
	
}
